﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Gios.Word;
using ZedGraph;
using Word = Microsoft.Office.Interop.Word;


namespace PostCFAST
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            work();
            word w = new word();
            //w.work1(); w.work2(); 
            //report2();
        }

        private void Form1_Shown(object sender, EventArgs e)
        {

        }
        ////////////////////////////////////////////////////////////////////////////////////////////
        private string n_csvS;
        private string n_csvN;

        public void work()
        {
            GetFileS();
            CsvToArrS();

            GetFileN();
            CsvToArrN();

            maik_arr_room();

            PointPairList lPP = new PointPairList();

            foreach (Room room in arrRoom)
            {
                // Adds new node as a child node of the currently selected node.
                TreeNode newNode = new TreeNode(room.nameRoom);
                treeView1.Nodes.Add(newNode);
                foreach (string s in arrOfpName)
                {
                    TreeNode newNode2 = new TreeNode(s);
                    newNode.Nodes.Add(newNode2);

                }


                room.make();
                List<double> arrVal_OD;
                string nameOFP = "OD";
                arrVal_OD = new List<double>();
                getOFP(arrVal_OD, room.nameRoom, "OD");
            }

        }
        List<Room> arrRoom = new List<Room>(); //
        List<string> arrOfpName = new List<string>(); //

        public List<List<string>> arrS = new List<List<string>>(); //
        public List<string> rowS = new List<string>(); //

        List<List<string>> arrN = new List<List<string>>(); //
        List<string> rowN = new List<string>(); //

        public double HR = 1.7; // рабочая высота 1.7м

        public void Calc_TR(int Work_Col)
        {
            int co, ro;
            double y; double x;
            String tmps;
            double curTime;
            double curHight;
            int Name_Param = 1;

            co = Work_Col; //Layer Height
            string tmp = arrN[Name_Param][co];
            if ((tmp == "Layer Height"))
            {
            }
            else
            {
                MessageBox.Show("The calculations are complete", "My Application", MessageBoxButtons.OKCancel, MessageBoxIcon.Asterisk);
                //error

            };

            tmp = arrN[1][co];
            tmp = arrN[2][co];
            // 
            for (ro = 0; ro < arrN.Count; ro++)
            {
                tmps = arrN[ro][0];
                try
                {
                    curTime = Convert.ToDouble(tmps);
                    curHight = Convert.ToDouble(arrN[ro][co]);
                    if (curHight <= HR)
                    {
                        TR = curTime; // pfgbcfnm d vfccbd rjvyfn 
                        break;
                    }
                }
                catch { ;}
            }
        }//Calc_TR



        /// <summary>
        /// 
        /// </summary>
        public double getTimeLimit(string nameRoom)
        {
            int co, ro;
            string curRoomName;
            string curUpperLower;
            string curOFPName;
            string tmps;
            double curTime;
            double curHight;
            for (co = 0; co < arrN[0].Count; co++) // цикл по столбцам 
            {
                curRoomName = arrN[0][co]; //Room 1
                //curUpperLower = arrS[1][co]; //Upper
                //curOFPName = arrS[2][co]; //OD

                if ((arrN[1][co] == "Layer Height") && (arrN[0][co] == nameRoom))
                {
                    for (ro = 3; ro < arrN.Count; ro++)
                    {
                        tmps = arrN[ro][0];
                        curTime = Convert.ToDouble(arrN[ro][0]);
                        curHight = Convert.ToDouble(arrN[ro][co]);
                        if (curHight <= HR)
                        {
                            TR = curTime; // pfgbcfnm d vfccbd rjvyfn 
                            return TR; //break;
                        }
                    }
                }
                else TR = -1;
            }
            return TR;
        }

        /// <summary>
        /// 
        /// </summary>
        public void getOFP(List<double> arrVal, string nameRoom, string nameOFP)
        {
            int co, ro;
            string curRoomName;
            string curUpperLower;
            string curOFPName;
            double TL;
            double curtime;
            double val;
            if (nameOFP == "Temp")
            {
                GetTemp(arrVal, nameRoom, nameOFP);
            }
            else
            {
                for (co = 0; co < arrS[0].Count; co++) // цикл по столбцам 
                {
                    curRoomName = arrS[0][co]; //Room 1
                    curUpperLower = arrS[1][co]; //Upper
                    curOFPName = arrS[2][co]; //OD
                    if ((curOFPName == nameOFP) && (curUpperLower == "Upper") && (curRoomName == nameRoom))
                    {
                        TL = getTimeLimit(nameRoom);
                        for (ro = 3; ro < arrS.Count; ro++)
                        {
                            curtime = Convert.ToDouble(arrS[ro][0]);
                            if (curtime < TL)
                            {
                                val = Convert.ToDouble(arrS[ro][co + 9]); //Lower !!!
                            }
                            else
                            {
                                val = Convert.ToDouble(arrS[ro][co]);
                            }
                            val = convert(val, nameOFP);
                            arrVal.Add(val);
                        }
                    }
                }
            }
        }
        public double getTimeLimOFP(List<double> arrVal, string nameOFP)
        {
            int i, co, ro;
            string curRoomName;
            string curUpperLower;
            string curOFPName;
            double TL;
            double curtime;
            double val;
            double LimOFP;
            List<double> arrTime = new List<double>();
            getTime(arrTime);
            LimOFP = getLimOFP(nameOFP);

            if (nameOFP == "OD")
            {
                for (i = 0; i < arrVal.Count; i++)
                {
                    if (arrVal[i] <= LimOFP)
                    {
                        return arrTime[i];
                    }
                }
            }

            for (i = 0; i < arrVal.Count; i++)
            {
                if (arrVal[i] >= LimOFP)
                {
                    return arrTime[i];
                }

            }
            return 0;
        }

        public void GetTemp(List<double> arrVal, string nameRoom, string nameOFP)
        {
            int co = 0, ro = 0;
            string curRoomName;
            string curUpperLower;
            string curOFPName;
            double curtime;
            double val;
            double TL;


            for (co = 0; co < arrN[0].Count; co++) // цикл по столбцам 
            {
                curRoomName = arrN[0][co];
                if (("Upper Layer Temp" == arrN[1][co]) && (curRoomName == nameRoom))
                {
                    TL = getTimeLimit(nameRoom);
                    for (ro = 3; ro < arrN.Count; ro++)
                    {
                        curtime = Convert.ToDouble(arrS[ro][0]);
                        if (curtime < TL)
                        {
                            val = Convert.ToDouble(arrN[ro][co + 1]); // Lower Layer Temp !!!
                        }
                        else
                        {
                            val = Convert.ToDouble(arrN[ro][co]);
                        }
                        arrVal.Add(val);
                    }
                }
            }
        }

        public void getTime(List<double> arrVal)
        {
            int co, ro;
            string curRoomName;
            string curUpperLower;
            string curOFPName;
            string nameRoom;
            string nameOFP;
            nameOFP = "Time";
            nameRoom = "SPECIES";
            co = 0;
            if ((arrS[1][co] == "Time") && (arrS[0][co] == "SPECIES"))
            {
                for (ro = 3; ro < arrS.Count; ro++)
                {
                    arrVal.Add(Convert.ToDouble(arrS[ro][co]));

                }
            }

        }



        /// <summary>
        /// 
        /// </summary>
        public class OFP
        {
            //public List<OFP> arr_OFP;
            public List<List<string>> arrS;
            public string nameOFP;
            public string nameRoom;
            public List<double> arrVal = new List<double>(); //
            /*
                        public OFP(List<List<string>> varrS)
                        {
                            arrS = varrS;
                        }
            */
            public void make(List<List<string>> varrS, string vnameRoom)
            {
                arrS = varrS;
                nameRoom = vnameRoom;
            }
        }

        /// <summary>
        /// 
        /// </summary>
        class Room
        {
            public string nameRoom;
            public List<OFP> arrOFP = new List<OFP>(); //    
            //public arrOFP ofp;
            public void make()
            {
                int co, ro;
                //for (co = 0; co < arrS[0].Count; co++) // цикл по столбцам {}
                OFP ofp;
                //ofp = new OD();
                //arrOFP.Add(ofp);
            }

        }


        /// <summary>
        /// 
        /// </summary>
        public void maik_arr_room()
        {
            arrOfpName.Add("O2");
            arrOfpName.Add("CO2");
            arrOfpName.Add("CO");
            arrOfpName.Add("HCN");
            arrOfpName.Add("HCL");
            arrOfpName.Add("H2O");
            arrOfpName.Add("OD");
            arrOfpName.Add("CT");
            arrOfpName.Add("TS");
            arrOfpName.Add("Temp");

            int co, ro;
            string oldRoomName, newRoomName;
            //oldRoomName = "NORMAL";newRoomName = "NORMAL";
            oldRoomName = "SPECIES"; newRoomName = "SPECIES";

            for (co = 0; co < arrS[0].Count; co++) // цикл по столбцам 
            {
                newRoomName = arrS[0][co];
                if (oldRoomName == newRoomName) continue;
                if ("" == newRoomName) continue;
                oldRoomName = newRoomName;
                Room room = new Room();
                room.nameRoom = newRoomName;

                arrRoom.Add(room);

            }
            int tmp = arrRoom.Count;

        }


        public void GetFileS()
        {
            string searchParameter = "*.s.csv"; // 
            string[] filenames = Directory.GetFiles(".");
            foreach (string name in filenames)
            {
                string[] splitted = searchParameter.Split('*');

                if (name.Contains(splitted[1]))
                {
                    Console.WriteLine(name); // вывод в консоль тоже можно заменить
                    n_csvS = name;
                }
            }

            //n_csvS = "cfastexp.s.csv"; // !!!

            recopy(n_csvS);
        }

        public void GetFileN()
        {
            string searchParameter = "*.n.csv"; //  
            string[] filenames = Directory.GetFiles(".");
            foreach (string name in filenames)
            {
                string[] splitted = searchParameter.Split('*');

                if (name.Contains(splitted[1]))
                {
                    Console.WriteLine(name); // вывод в консоль тоже можно заменить
                    n_csvN = name;
                }
            }

            //n_csvN = "cfastexp.n.csv";//!!!

            recopy(n_csvN);
        }



        public void recopy(string filename)
        {
            return;
            string s;
            string InFileName;
            string OutFileName;
            InFileName = filename;
            OutFileName = InFileName + ".XLS" + ".csv";
            StreamWriter sw = new StreamWriter(OutFileName);
            StreamReader reader = new StreamReader(InFileName);
            while ((s = reader.ReadLine()) != null)
            {
                StringBuilder sb = new StringBuilder(s);
                sb.Replace(',', ';');
                sw.WriteLine(sb);
            }
            reader.Close();
            sw.Close();
            {
                System.Diagnostics.Process MyProc = new System.Diagnostics.Process();
                MyProc.StartInfo.FileName = OutFileName;

                //MyProc.Start();//
            }
        }

        /// <summary>
        ///  
        /// </summary>


        public void CsvToArrS()
        {                //string ss; 
            string s;
            int sringcount = 0;
            StreamReader reader = new StreamReader(n_csvS);
            while ((s = reader.ReadLine()) != null)
            {
                rowS = new List<string>();
                //string[] ss = s.Split(',', ';');
                string[] ss = s.Split(',');
                //row = ss;
                for (int i = 0; i < ss.Length; i++)
                {
                    rowS.Add(ss[i]);     //object col;col.Add(str[i]);
                }
                arrS.Add(rowS); //строка добавляется в массив
                //a = Int32.Parse(split[0]);b = Int32.Parse(split[1]);name = split[2];fullName = split[3];
                sringcount++;
            }
            reader.Close();
        }

        public void CsvToArrN()
        {
            {
                string s;
                int sringcount = 0;
                StreamReader reader = new StreamReader(n_csvN);
                while ((s = reader.ReadLine()) != null)
                {
                    rowN = new List<string>();
                    //string[] ss = s.Split(',', ';');
                    string[] ss = s.Split(',');
                    //row = ss;
                    for (int i = 0; i < ss.Length; i++)
                    {
                        rowN.Add(ss[i]); //object col;col.Add(str[i]);
                    }
                    arrN.Add(rowN); //строка добавляется в массив
                    //a = Int32.Parse(split[0]);b = Int32.Parse(split[1]);name = split[2];fullName = split[3];
                    sringcount++;
                }
                reader.Close();
            }
        }
        public double convert(double ValCFAST, string curOFPName)
        {
            double res = 0;

            int caseSwitch = 1;
            switch (curOFPName)
            {
                // OD оптическая плотность в обратных метрах
                // L(м) дальность видимости в метрах 
                case "OD":
                    if (ValCFAST <= 0.01) ValCFAST = 0.01;
                    res = 2.38 / ValCFAST;
                    break;
                case "O2":
                    /*Критическое значние по кислороду (О2) - 0,226кг/м3. 
                    * Разделить это значение на 1,29кг/м3 - плотность воздуха - получится концентрация, 0.175, это 17.5%.
                    */
                    res = (ValCFAST / 100) * 1.29;
                    break;
                case "CO2":
                    res = (ValCFAST / 100) * 1.29;
                    break;
                case "CO":
                    res = (ValCFAST) * 1.29 / 1000000;
                    break;
                case "HCL":  //Хлороводород
                    res = (ValCFAST) * 1.29 / 1000000;
                    break;
                default:
                    res = ValCFAST;
                    break;
            }
            return res;
        }
        public double getLimOFP(string curOFPName)
        {
            double res = 0;

            int caseSwitch = 1;
            switch (curOFPName)
            {
                case "OD":
                    res = 20;
                    break;
                case "O2":
                    res = 0.226; //Критическое значние по кислороду (О2) - 0,226кг/м3.        
                    break;
                case "CO2":
                    res = 0.11;
                    break;
                case "CO":
                    res = 0.00116;
                    break;
                case "HCL":  //Хлороводород
                    res = 0.000023;
                    break;
                case "Temp":
                    res = 70;
                    break;
                default:
                    res = 0.00001;
                    break;
            }
            return res;


        }

        string ofp_name;
        string title;
        string FormText;
        public PointPairList lPP;

        public string XAxisTitleText;
        public string YAxisTitleText;
        public double Lim_OFP;
        public double TR;

        private void treeView1_AfterSelect2(string nameRoom , string nameOFP)
        {
            int i;
            double TL;
            List<double> arrOfp = new List<double>();
            List<double> arrTime = new List<double>();

            // Determine by checking the Text property.

                TL = getTimeLimit(nameRoom);
                getOFP(arrOfp, nameRoom, nameOFP);
                getTime(arrTime);
                //PointPairList list = new PointPairList();
                lPP = new PointPairList();
                for (i = 0; i < arrOfp.Count; i++)
                {
                    lPP.Add(arrTime[i], arrOfp[i]);

                }
                XAxisTitleText = "время, с" + "(время опускания слоя дыма = " + TL.ToString() + " cек.)"; ;
                YAxisTitleText = nameOFP;
                title = "помещение: " + nameRoom + " " + "ОФП: " + nameOFP; // +" " + "(время опускания слоя дыма = " + TL.ToString() + " cек.)";
                this.Text = title;
                this.Text = "проба";
                ofp_name = nameOFP;
                Lim_OFP = getLimOFP(nameOFP);
                double TimeLimOFP;
                TimeLimOFP = getTimeLimOFP(arrOfp, nameOFP);
                textBox1.Text = " помещение: " + nameRoom + " " +
                                "\r\n ОФП: " + nameOFP +
                                "\r\n предельное значение ОФП = " + Lim_OFP.ToString() + " " +
                                "\r\n время достижение предела по ОФП = " + TimeLimOFP.ToString() +
                                "\r\n (время опускания слоя дыма = " + TL.ToString() + " cек.)";

                DrawGraph(lPP);
                ////////////////////////// 
                int co = 1, ro = 0;
                DataGridViewCell txtCell2;
                for (i = 0; i < arrOfp.Count; i++, ro++)
                {
                    dataGridView1.Rows.Add();

                    txtCell2 = dataGridView1.Rows[ro].Cells[0];
                    txtCell2.Value = arrTime[i];

                    txtCell2 = dataGridView1.Rows[ro].Cells[1];
                    txtCell2.Value = arrOfp[i];
                }
        }

        private void treeView1_AfterSelect(object sender, TreeViewEventArgs e)
        {
            // Determine by checking the Text property.
            string nameOFP = e.Node.Text;
            string nameRoom = "";
            if (e.Node.Level == 1)
            {
                nameRoom = e.Node.Parent.Text;
                treeView1_AfterSelect2(nameRoom, nameOFP);
            }
        }

        ///////////////////////////////////////////////////////////////////////////////////////////////////////////////
        private void DrawGraph(PointPairList lPP)
        {
            this.Text = "Название формы";
            this.Text = FormText;
            // Получим панель для рисования
            GraphPane pane = zedGraph.GraphPane;

            // Очистим список кривых на тот случай, если до этого сигналы уже были нарисованы
            pane.CurveList.Clear();

            // Создадим кривую с названием "Sinc", 
            // которая будет рисоваться голубым цветом (Color.Blue),
            // Опорные точки выделяться не будут (SymbolType.None)

            LineItem myCurve = pane.AddCurve(ofp_name, lPP, Color.Blue, SymbolType.Circle);
            /*
                        // Создадим кривую с названием "Sin",
                        // которая будет рисоваться красным цветом (Color.Red),
                        // Опорные точки будут выделяться плюсиками (SymbolType.Plus)
                        LineItem f2_curve = pane.AddCurve(Lim_OFP_, f2_list, Color.Red, SymbolType.None);
            */
            pane.Title.Text = title;

            pane.XAxis.Title.Text = XAxisTitleText; // "время, с";
            pane.YAxis.Title.Text = YAxisTitleText; // "высота, м";

            zedGraph.IsShowPointValues = true;
            // Вызываем метод AxisChange (), чтобы обновить данные об осях. 
            // В противном случае на рисунке будет показана только часть графика, 
            // которая умещается в интервалы по осям, установленные по умолчанию
            zedGraph.AxisChange();
            ///

            // Линию рисуем после обновления осей с помощью AxisChange (),
            // так как мы будем использовать значения
            // Нарисуем горизонтальную пунктирную линию от левого края до правого на уровне y = 0.5
            double level = Lim_OFP;
            LineObj line = new LineObj(pane.XAxis.Scale.Min, level, pane.XAxis.Scale.Max, level);
            // Стиль линии - пунктирная
            line.Line.Style = System.Drawing.Drawing2D.DashStyle.Dash;
            line.Line.Color = Color.Red;
            pane.GraphObjList.Clear();
            // Добавим линию в список отображаемых объектов
            pane.GraphObjList.Add(line);


            /*           
                      double levelX = TR;
                      LineObj lineVert = new LineObj(levelX, pane.YAxis.Scale.Min, levelX, pane.YAxis.Scale.Max);
                      // Стиль линии - пунктирная
                      lineVert.Line.Style = System.Drawing.Drawing2D.DashStyle.Dot;
                      //lineVert.Line.Style = System.Drawing.Drawing2D.DashStyle.Dot;
                      // Добавим линию в список отображаемых объектов
                      pane.GraphObjList.Add(lineVert);
            */

            // Обновляем график
            zedGraph.Invalidate();
           // zedGraph.SaveAsBitmap();
        }

        private void zedGraph_Load(object sender, EventArgs e)
        {

        }

        private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {

        }

        private void tableLayoutPanel1_Paint(object sender, PaintEventArgs e)
        {

        }

        private void treeView1_AfterSelect_1(object sender, TreeViewEventArgs e)
        {
            treeView1_AfterSelect(sender, e);
        }

        private void textBox1_TextChanged(object sender, EventArgs e)
        {

        }

        [STAThread]
        public void Report()
        {
            // Create a new Word Document
            //WordDocument rd = new WordDocument(WordDocumentFormat.Letter_8_5x11_Horizontal);
            WordDocument rd = new WordDocument(WordDocumentFormat.A4);
            /*
                      // Sets a text effect using a custom control word. See RTF spefications for further implementations.
                      rd.WriteControlWord("animtext3");

                      // I think that there's no need of explanaition...
                      rd.SetFontBackgroundColor(Color.Yellow);
                      rd.SetForegroundColor(Color.Red);
                      rd.SetFont(new Font("Arial", 30));
                      rd.SetTextAlign(WordTextAlign.Center);

                      rd.WriteLine("GIOS WORD.NET Features Test");

                      // Reset the text effect using a custom control word.
                      rd.WriteControlWord("animtext0");

                      // Resets the colors
                      rd.SetFontBackgroundColor();9
                      rd.SetForegroundColor(Color.Black);
            */
            foreach (Room room in arrRoom)
            {
                int ROW;
                List<double> arrOfp = new List<double>();
                List<double> arrTime = new List<double>();

                rd.WriteLine(room.nameRoom);


                string nameOFP = "OD";
                string nameRoom = room.nameRoom;
                int i;
                double TL;
                TL = getTimeLimit(nameRoom);
                getOFP(arrOfp, nameRoom, "OD");
                ROW = arrOfp.Count;
                //getOFP(arrOfp, nameRoom, nameOFP);
                getTime(arrTime);

                WordTable rt = rd.NewTable(new Font("Times", 8), Color.Blue, ROW + 1, arrOfpName.Count + 1, 2);
                //WordTable rt = rd.NewTable(new Font("Arial", 12), Color.Blue, arrOfp.Count, 1 + 1, 2);

                rt.Rows[0][0].Write(@"время TIME");
                int ro = 1;
                for (i = 0; i < ROW - 1; i++, ro++)
                {
                    rt.Rows[ro][0].Write(arrTime[i].ToString("0.0"));
                }
                rt.SaveToDocument(3000, 0);

                int co = 1;
                foreach (string s in arrOfpName)
                {
                    getOFP(arrOfp, nameRoom, s);
                    rt.Rows[0][co].Write(s);
                    ro = 1;
                    for (i = 0; i < ROW - 1; i++, ro++)
                    {
                        //rt.Rows[ro][0].Write(arrTime[i].ToString("0.0"));
                        rt.Rows[ro][co].Write(arrOfp[i].ToString("#,##0.0"));
                    }

                    rt.SaveToDocument(3000, 0);
                    rd.WriteLine();
                    co++;

                }

                /*              
                              foreach (string s in arrOfpName)
                              {
                                  int co = 1, ro = 0;
                                  DataGridViewCell txtCell2;
                                  string nameOFP = s;
                                  string nameRoom = room.nameRoom;
                                  List<double> arrOfp = new List<double>();
                                  List<double> arrTime = new List<double>();
                                  int i;
                                  double TL;
                                  TL = getTimeLimit(nameRoom);
                                  getOFP(arrOfp, nameRoom, nameOFP);
                                  getTime(arrTime);

                                  rd.WriteLine(s);
                                  WordTable rt = rd.NewTable(new Font("Arial", 12), Color.Blue, arrOfp.Count, 2, 2);

                                  for (i = 0; i < arrOfp.Count; i++, ro++)
                                  {
                                      rt.Rows[ro][0].Write(arrTime[i].ToString());
                                      rt.Rows[ro][1].Write(arrOfp[i].ToString());
                                  }

                                  rt.SaveToDocument(3000, 0);
                                  rd.WriteLine();

                              }
                */
                int[] ColumnusWithArray = { 150, 150, 150, 150, 150, 150, 150, 150, 150, 150, 150 };
                rt.SetColumnsWidth(ColumnusWithArray);
                //   Selection.Tables(1).AutoFitBehavior (wdAutoFitWindow)

                rd.WriteLine(); rd.WriteLine(); rd.WriteLine();
            }


            rd.WriteLine();

            WordTable rt1 = rd.NewTable(new Font("Arial", 12), Color.Red, 2, 2, 2);
            rt1.Rows[0][0].Write("hello");
            rt1.SetBorders(Color.Red, 2, true, true, true, true);
            rt1.SaveToDocument(3000, 4000);
            rd.WriteLine();

            WordTable rt2 = rd.NewTable(new Font("Arial", 12), Color.Blue, 2, 4, 2);
            rt2.Rows[0][0].Write("hello");
            rt2.SaveToDocument(3000, 0);
            rd.WriteLine();

            // We can also set the starting page of the document.
            //          rd.SetPageNumbering(999);

            // In a object oriented document description, we can set the header
            // and the footer just we want to do it!
            rd.HeaderStart();
            rd.SetTextAlign(WordTextAlign.Center);
            rd.SetFont(new Font("Verdana", 10, FontStyle.Bold));
            rd.Write(" ");
            rd.WriteLine();
            rd.HeaderEnd();

            /*
                      rd.FooterStart();
                      rd.SetTextAlign(WordTextAlign.Center);
                      rd.SetFont(new Font("Verdana", 10, FontStyle.Bold));
                      rd.Write("Copyright ©   - All rigths reserved");
                      rd.FooterEnd();
            */
            //          rd.NewPage();

            rd.SetTextAlign(WordTextAlign.Left);
            rd.WriteLine();
            rd.WriteLine("And this is a list using the line indent:");
            rd.WriteLine();
            // this sets the distance from the margin
            rd.SetParagraph(500);
            rd.WriteLine("- One1");
            rd.WriteLine("- Two2");
            rd.WriteLine("- Three3");
            // resets the paragraph
            rd.SetParagraph();
            rd.WriteLine();
            rd.WriteLine("That's all... Enjoy!");

            //rd.SaveToFile("Example2.doc");          System.Diagnostics.Process.Start("Example2.doc");


            rd.SaveToFile("Example2.doc");
            System.Diagnostics.Process.Start("Example2.doc");
        }


        /// <summary>
        /// 
        /// </summary>
  public void report2()
  {   //using Word = Microsoft.Office.Interop.Word;   //return;
    Word.Application wordApplication = new Word.Application(); //объявили переменную типа Word
    Object template = Type.Missing;
    Object newTemplate = Type.Missing;
    Object documentType = Type.Missing;
    Object visible = Type.Missing;
    wordApplication.Documents.Add(ref template, ref newTemplate, ref documentType, ref visible);//добавили в проложение документ
    Word.Document doc = wordApplication.ActiveDocument;
    wordApplication.Visible = true; //делаем что бы word не работал в фоновом режиме
///
    //wordApplication.Options.CheckSpellingAsYouType = false;
    //wordApplication.Options.CheckGrammarAsYouType = false;

    Object r = Type.Missing;
    Word.Paragraph par = doc.Content.Paragraphs.Add(ref r);//дабавляем в документ параграф

    Word.Document worddocument = wordApplication.ActiveDocument;
    Word.Application wordapp = wordApplication;



            Object missing = Type.Missing;
            Word.Range rng = doc.Range(ref missing, ref missing); //получаем текстовую область параграфf

///
          foreach (Room room in arrRoom)
          {
              object unit;
              object extend;

              int ROW;
              List<double> arrOfp = new List<double>();
              List<double> arrTime = new List<double>();
             
              string nameOFP = "OD";
              string nameRoom = room.nameRoom;
              int i;
              double TL;
              TL = getTimeLimit(nameRoom);
              getOFP(arrOfp, nameRoom, "OD");
              ROW = arrOfp.Count;
              //getOFP(arrOfp, nameRoom, nameOFP);
              getTime(arrTime);

              Word.Paragraphs wordparagraphs;
              wordparagraphs = worddocument.Paragraphs;
              Word.Paragraph wordparagraph;
              wordparagraph = (Word.Paragraph)wordparagraphs[1];
              //wordparagraph.Range.Text = nameRoom;

              unit = Word.WdUnits.wdStory;
              extend = Word.WdMovementType.wdMove;
              wordapp.Selection.EndKey(ref unit, ref extend);
              wordapp.Selection.TypeParagraph();

              unit = Word.WdUnits.wdStory;
              extend = Word.WdMovementType.wdMove;
              wordapp.Selection.EndKey(ref unit, ref extend);
              wordapp.Selection.Range.Text = nameRoom;
              
              unit = Word.WdUnits.wdStory;
              extend = Word.WdMovementType.wdMove;
              wordapp.Selection.EndKey(ref unit, ref extend);
              //Word.Table wordtable2 = worddocument.Tables.Add(wordapp.Selection.Range, 4, 4, ref defaultTableBehavior,ref autoFitBehavior);
              //rng.Tables.Add(wordapp.Selection.Range, 2 + 1, 3 + 1, ref missing, ref missing);//вставляем в текстовую область таблицу
              rng.Tables.Add(wordapp.Selection.Range, ROW + 1, arrOfpName.Count + 1, ref missing, ref missing);//вставляем в текстовую область таблицу
              Word.Table tbl = doc.Tables[doc.Tables.Count];//для удобства работы присваиваем таблицу переменной/// 
              // rng.Tables.Add(doc.Paragraphs[doc.Paragraphs.Count].Range, ROW +1 , arrOfpName.Count + 1, ref missing, ref missing);//вставляем в текстовую область таблицу
              
              //Word.Table rt = tbl;

              tbl.Cell(1, 1).Range.Text = @"время TIME";
              int ro = 2;
              for (i = 0; i < ROW-1; i++, ro++)
              {
                  tbl.Cell(ro, 1).Range.Text = arrTime[i].ToString("0.0");
              }
              
              int co = 2;
              foreach(string s in arrOfpName)
              {
                  treeView1_AfterSelect2(nameRoom, s);
                  string ImageFileMame = "tmp.png";
                  string ImageFileMame2; 
                  SavePaneImage(ImageFileMame);
                  object f = false;
                  object t = true;
                  object left = Type.Missing;
                  object top = Type.Missing;
                  object width = 300;
                  object height = 300;
                  object range = Type.Missing;
                  //Microsoft.Office.Interop.Word.WdWrapType wrap = Microsoft.Office.Interop.Word.WdWrapType.wdWrapSquare;
                  //doc.InlineShapes.AddPicture(ImageFileMame , ref f, ref t, ref range);
                  //doc.Shapes.AddPicture(ImageFileMame, ref f, ref t, ref left, ref top, ref width, ref height, ref range).WrapFormat.Type = wrap;

                  unit = Word.WdUnits.wdStory;
                  extend = Word.WdMovementType.wdMove;
                  wordapp.Selection.EndKey(ref unit, ref extend);
                   range = wordapp.Selection.Range;
                  ImageFileMame2 = Application.StartupPath + @"\" + ImageFileMame;
                  doc.InlineShapes.AddPicture(ImageFileMame2, ref f, ref t, ref range);

                  getOFP(arrOfp, nameRoom, s);
                  tbl.Cell(1, co).Range.Text = s ;
                  ro = 2;
                  for (i = 0; i < ROW-1; i++, ro++)
                  {
                      //rt.Rows[ro][0].Write(arrTime[i].ToString("0.0"));
                      tbl.Cell(ro, co).Range.Text = arrOfp[i].ToString("#,##0.0"); 
                  }
                  co++;
                  arrOfp.Clear(); 
              }


              //   Selection.Tables(1).AutoFitBehavior (wdAutoFitWindow)
                          Word.Border[] borders = new Word.Border[6];//массив бордеров
            borders[0] = tbl.Borders[Word.WdBorderType.wdBorderLeft];//левая граница 
            borders[1] = tbl.Borders[Word.WdBorderType.wdBorderRight];//правая граница 
            borders[2] = tbl.Borders[Word.WdBorderType.wdBorderTop];//нижняя граница 
            borders[3] = tbl.Borders[Word.WdBorderType.wdBorderBottom];//верхняя граница
            borders[4] = tbl.Borders[Word.WdBorderType.wdBorderHorizontal];//горизонтальная граница
            borders[5] = tbl.Borders[Word.WdBorderType.wdBorderVertical];//вертикальная граница
            foreach (Word.Border border in borders)
            {
                border.LineStyle = Word.WdLineStyle.wdLineStyleSingle;//ставим стиль границы 
                border.Color = Word.WdColor.wdColorBlack;//задаем цвет границы
            }
          }//foreach (Room room in arrRoom)

          Object saveChanges = Word.WdSaveOptions.wdPromptToSaveChanges;
          Object originalFormat = Word.WdOriginalFormat.wdWordDocument;
          Object routeDocument = Type.Missing;
          wordapp.Quit(ref saveChanges,
                       ref originalFormat, ref routeDocument);
          wordapp = null;

      }//report2()


        /// <summary>
        /// Сохранить картинку панели, указанной с помощью индекса
        /// </summary>
        /// <param name="index"></param>
        private void SavePaneImage(string ImageFileName)
        {
            //ImageFileName = "tmp.png";
            int index = 0;
            
                // Получием панель по ее индексу
                GraphPane pane = zedGraph.MasterPane.PaneList[index];

                // Получаем картинку, соответствующую панели
                Bitmap bmp = pane.GetImage();

                // Сохраняем картинку средствами класса Bitmap
                    bmp.Save(ImageFileName, ImageFormat.Png);
                
        }

        private void button1_Click(object sender, EventArgs e)
        {
            report2();
        }


    }
}
